package com.zkyc.framework.website.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.mapper.PiMapper;
import com.zkyc.framework.common.pojo.Pi;
import com.zkyc.framework.common.pojo.User;
import com.zkyc.framework.common.utils.SqlConditionUtil;
import com.zkyc.framework.common.utils.WebsiteUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.website.client.UserClient;
import com.zkyc.framework.website.service.PiService;
import com.zkyc.framework.website.util.TokenUserUtil;
import com.zkyc.framework.website.vo.PiPageVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.annotation.Resource;
import java.util.*;

/**
 * (Pi)表服务实现类
 *
 * @author libingchuan
 * @since 2022-11-15 16:22:10
 */
@Service("piService")
@Slf4j
public class PiServiceImpl implements PiService {
    @Resource
    private PiMapper piMapper;

    @Resource
    private UserClient userClient;


    public static final String PI_BASIC = "http://gateway.dmind.zhejianglab.com/rest/davinci-0.3-rc/api/v3/zj/34/fetchData";
    public static final String PI_RESEARCH = "http://gateway.dmind.zhejianglab.com/rest/davinci-0.3-rc/api/v3/zj/35/fetchData";

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Pi queryById(Integer id) {
        return this.piMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryByPage(PiPageVo piPageVo) throws Exception {
        if (piPageVo == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        piPageVo.checkParam();
        Page<Pi> page = new Page<>(piPageVo.getPage(), piPageVo.getSize());
        QueryWrapper<Pi> queryWrapper = (QueryWrapper<Pi>) SqlConditionUtil.getQueryWrapper(SqlHelper.table(Pi.class).getTableName(), piPageVo, new QueryWrapper());
        queryWrapper.eq("website_id",WebsiteUtil.getWebsiteId());
        queryWrapper.orderByDesc("gmt_created");
        IPage<Pi> page1 = piMapper.selectPage(page, queryWrapper);
        return ResultVO.data(page1);
    }

    /**
     * 查询
     *
     * @return 查询结果
     */
    @Override
    public ResultVO queryList() {
        return ResultVO.data(piMapper.selectList(null));
    }


    /**
     * 新增数据
     *
     * @param pi 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO insert(Pi pi) {
        if (pi == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        JSONArray basicInformation = setInformation(pi);
        pi.setPiInformation(basicInformation.toJSONString());
        pi.setWebsiteId(WebsiteUtil.getWebsiteId());
        //插入数据库
        piMapper.insert(pi);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    private JSONArray setInformation(Pi pi) {
        assert pi != null;
        Optional<Pi> optionalPi = Optional.of(pi);
        String organizationOne = optionalPi.map(Pi::getOrganizationOne).orElse("其他");
        String organizationTwo = optionalPi.map(Pi::getOrganizationTwo).orElse("其他");
        pi.setOrganizationOne(organizationOne);
        pi.setOrganizationTwo(organizationTwo);
        //创建PI的存储格式,拉取下来的接口就是这种格式
        JSONArray basicInformation = new JSONArray();
        //basicjsonObject存储基本信息
        JSONObject basicjsonObject = new JSONObject();
        basicjsonObject.put("name", pi.getName());
        basicjsonObject.put("ssbm", organizationOne);
        basicjsonObject.put("dept_name", organizationTwo);
        basicjsonObject.put("zw", pi.getPosition());
        basicjsonObject.put("photo", pi.getPhoto());
        basicInformation.add(basicjsonObject);
        //intrudoceArray存储介绍
        JSONArray intrudoceArray = new JSONArray();
        JSONObject introducejsonObject = new JSONObject();
        introducejsonObject.put("content", pi.getIntroduce());
        intrudoceArray.add(introducejsonObject);
        basicInformation.add(intrudoceArray);
        return basicInformation;
    }

    @Override
    public ResultVO insert(List<String> userCodes) {
        Integer successCount = 0;
        Integer failCount = 0;
        ArrayList<String> duplicateList = new ArrayList<>();
        ArrayList<String> nullList = new ArrayList<>();
        for (String userCode : userCodes) {
            //调用PI_BASIC接口
            String piBasicString = HttpRequest.get(PI_BASIC)
                    .form("user_code", userCode)
                    .execute().body();
            //调用PI_RESEARCH接口
            String piBasicResearch = HttpRequest.get(PI_RESEARCH)
                    .form("user_code", userCode)
                    .execute().body();
            //处理数据
            JSONObject piBasicJsonOriginal = JSONObject.parseObject(piBasicString);
            JSONObject piResearchJsonOriginal = JSONObject.parseObject(piBasicResearch);
            JSONArray piBasicArray = piBasicJsonOriginal.getJSONObject("payload").getJSONArray("resultList");
            JSONArray piResearchArray = piResearchJsonOriginal.getJSONObject("payload").getJSONArray("resultList");
            if (piBasicArray.size() > 0) {
                piBasicArray.add(piResearchArray);
            } else {
                failCount++;
                nullList.add(userCode);
                continue;
            }
            QueryWrapper<Pi> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_code", userCode);
            queryWrapper.eq("website_id",WebsiteUtil.getWebsiteId());
            Pi pi = piMapper.selectOne(queryWrapper);
            if (pi == null) {
                pi = new Pi();
                pi.setIsVerified(NumberConstant.NUMBER_0);
                pi.setUserCode(userCode);
                pi.setPiInformation(piBasicArray.toString().replaceAll("https://file.zhejianglab.com","https://www.zhejianglab.com"));
                //姓名
                pi.setName(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).get("name").toString());
                String currentUserId = TokenUserUtil.getCurrentUserId();
                if (currentUserId != null) {
                    ResultVO<?> userById = userClient.getUserById(currentUserId);
                    JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
                    User user = JSONObject.parseObject(jsonObject.getString("data"), User.class);
                    pi.setCreateUserName(user.getUsername());
                }
                pi.setOrganizationTwo(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("dept_name", " ").toString());
                pi.setOrganizationOne(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("ssbm", " ").toString());
                pi.setPhoto(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("photo", " ").toString().replaceAll("https://file.zhejianglab.com","https://www.zhejianglab.com"));
                pi.setPosition(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).getOrDefault("zw", " ").toString());
                //设置介绍
                JSONArray jsonArray = piBasicArray.getJSONArray(NumberConstant.NUMBER_1);
                for (int i = 0; i < jsonArray.size(); i++) {
                    String introduce = "";
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (StringUtils.isNotBlank(jsonObject.get("content").toString())) {
                        introduce += jsonObject.get("name").toString() + ": " + jsonObject.get("content").toString() + ";<br/>";
                    }
                    if (introduce.length() > 6) {
                        pi.setIntroduce(introduce.substring(0, introduce.length() - 6));
                    } else {
                        pi.setIntroduce(introduce);
                    }
                }
                pi.setWebsiteId(WebsiteUtil.getWebsiteId());
                piMapper.insert(pi);
                successCount++;
                log.info("pi添加成功:{}", pi);
            } else {
                //更新pi
                failCount++;
                duplicateList.add(userCode);
                pi.setPiInformation(piBasicArray.toString().replaceAll("https://file.zhejianglab.com","https://www.zhejianglab.com"));
                pi.setName(piBasicArray.getJSONObject(NumberConstant.NUMBER_0).get("name").toString());
                piMapper.updateById(pi);
                log.info("pi更新成功:{}", pi);
                log.info("对象已被添加:{}", pi);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("successCount", successCount);
        jsonObject.put("failCount", failCount);
        jsonObject.put("duplicateList", duplicateList);
        jsonObject.put("nullList", nullList);
        return ResultVO.data(jsonObject);
    }

    /**
     * 修改数据
     *
     * @param pi 实例对象
     * @return 实例对象
     */
    @Override
    public ResultVO update(Pi pi) {
        if (pi == null || pi.getId() == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(pi.getId()) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        JSONArray basicInformation = setInformation(pi);
        pi.setPiInformation(basicInformation.toJSONString());
        piMapper.updateById(pi);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public ResultVO deleteById(Integer id) {
        if (id == null) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        if (queryById(id) == null) {
            return ResultVO.fail(ResultCode.SERVE_ERROR);
        }
        piMapper.deleteById(id);
        return ResultVO.success(ResultCode.SUCCESS);
    }

    @Override
    public ResultVO getOrganization(Integer type) {
        QueryWrapper<Pi> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("website_id",WebsiteUtil.getWebsiteId());
        List<Pi> piList = piMapper.selectList(queryWrapper);
        LinkedHashSet<String> organizationName = new LinkedHashSet<>();
        organizationName.add("其他");
        for (Pi pi : piList) {
            if (type == 1 && StringUtils.isNotBlank(pi.getOrganizationOne())) {
                organizationName.add(pi.getOrganizationOne());
            }
            if (type == 2 && StringUtils.isNotBlank(pi.getOrganizationTwo())) {
                organizationName.add(pi.getOrganizationTwo());
            }

        }
        return ResultVO.data(organizationName);
    }
}
